﻿using System;
using System.Collections.Generic;

using RexToy.IoC;
using RexToy.Template;

namespace Studio.Model
{
    public class TemplateRenderModel
    {
        private ITemplateEngine _engine;
        public TemplateRenderModel()
        {
            IKernal k = KernalFactory.Create("main");
            _engine = k.Lookup<ITemplateEngine>();
        }

        private string _input;
        public string Input
        {
            get { return _input; }
            set
            {
                _input = value;

                try
                {
                    _output = _engine.RenderRaw(_input);
                    _error = null;
                }
                catch (Exception ex)
                {
                    _error = ex;
                }
            }
        }

        private string _output;
        public string Output
        {
            get { return _output; }
        }

        private Exception _error;
        public Exception Error
        {
            get { return _error; }
        }

        public void AssignContext(IDatabaseModel model)
        {
            string name = "tables";
            if (model == null)
            {
                _engine.Context.RemoveVar(name);
            }
            else
            {
                _engine.Context.Assign(name, model.Tables);
            }

            try
            {
                _output = _engine.RenderRaw(_input);
                _error = null;
            }
            catch (Exception ex)
            {
                _error = ex;
            }
        }
    }
}
